import React, { useEffect, useRef, useState } from "react";
import Alymodel from "../../mysql_interface/model";
import { asyncInquireusertotpdataid9, asyncossupload8 } from "../api/api";
import useMessage from "antd/es/message/useMessage";
interface P {
    getuser: Alymodel.IMuser,
    cid: number
    num: number
}

const Sectionw: React.FunctionComponent<P> = (p) => {
    const [x, setx] = useState(true)
    const [messageApi, contextHolder] = useMessage();

    const aliyunPreview = useRef<HTMLIFrameElement>(null)
    useEffect(() => {
        window.addEventListener(
            "message",
            message,
            false
        );
        return () => {
            window.removeEventListener('message', message)
        }
    }, [x])
    function message(e: MessageEvent<any>) {
        let res;
        if (e.data && typeof e.data === "string") {
            res = JSON.parse(e.data);
            switch (res.action) {
                case "preview.ready":
                    init(p.cid);
                    break;
                case "logic.refreshToken":
                    setToken();
                    break;
                case "message.error":
                    break;
            }
        }
    }
    useEffect(() => {
        setx(true)
        Refresh()
    }, [p.cid])

    async function setToken() {
        const data = await asyncossupload8();
        sendMessage("logic.setToken", {
            region: "oss-cn-beijing",
            accessKeyId: data.accessKeyId,
            accessKeySecret: data.accessKeySecret,
            stsToken: data.securityToken,
            bucket: "hterobot-pdf",
        });
    }
    async function init(cid: number) {
        if (!x) return;
        setx(false);
        const { userid } = p.getuser;
        const arr = await asyncInquireusertotpdataid9({
            course_ID: cid,
            num: p.num,
        });
        const url = arr.TgtUri;
        if (arr) {
            const {
                accessKeyId,
                accessKeySecret,
                securityToken,
            } = await asyncossupload8();
            sendMessage("preview.init", {
                url,
                region: "oss-cn-beijing",
                bucket: "hterobot-pdf",
                accessKeyId,
                accessKeySecret,
                stsToken: securityToken,
                wmType: 1,
                wmValue: String(userid),
                wmColor: "rgba(192, 192, 192, 0.2)",
                copy: 1
            });
        } else {
            messageApi.error('没有权限哦！');
        }
    }

    function sendMessage(action: string, data: any) {
        if (aliyunPreview.current) {
            aliyunPreview.current.contentWindow?.postMessage(json2str({
                action: action,
                data: data,
            }),
                "*")

        }
    }

    function Refresh() {
        if (aliyunPreview.current && aliyunPreview.current.contentWindow) {
            aliyunPreview.current.contentWindow.location.href = `https://preview.imm.aliyun.com/index.html?_q=${Math.random()}`
        }
    }

    function json2str(obj: { action: string, data: any }) {
        return JSON.stringify(obj, function (key, val) {
            if (typeof val === "function") {
                val = val.toString();
            }
            return val;
        });
    }

    return <iframe
        id="aliyunPreview"
        ref={aliyunPreview}
        src="https://preview.imm.aliyun.com/index.html"
        allowFullScreen
        frameBorder="0"
        scrolling="no"
        style={{ width: '100%', minHeight: '600px' }}
    />
}

export default Sectionw